package com.bsiprosoft.ejerciciosandoidproject;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

/**
 * Created by pbastidas on 12/16/13.
 */
public class EjemploMultiTouch extends Activity implements View.OnTouchListener {

    private TextView textView;
    private int[] index;
    private float[] posX;
    private float[] posY;
    private boolean[] pulsado;

    public EjemploMultiTouch() {
        index = new int[10];
        posX = new float[10];
        posY = new float[10];
        pulsado = new boolean[10];
    }

    private void escribirPosicion() {
        StringBuilder msg = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            msg.append("Pulsado: ");
            msg.append(pulsado[i]);
            msg.append("Index: ");
            msg.append(index[i]);
            msg.append("; X: ");
            msg.append(posX[i]);
            msg.append("; Y: ");
            msg.append(posY[i]);
            msg.append("\n");
        }

        textView.setText(msg.toString());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        textView = new TextView(this);

        textView.setOnTouchListener(this);
        textView.setText("Toca la pantalla con varios dedos... :D");

        setContentView(textView);
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {

        // get pointer index from the event object
        int pointerIndex = event.getActionIndex();

        // get pointer ID
        int pointerId = event.getPointerId(pointerIndex);

        // get masked (not specific to a pointer) action
        int maskedAction = event.getActionMasked();

        index[pointerId] = pointerIndex;

        switch (maskedAction) {

            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN: {
                // We have a new pointer. Lets add it to the list of pointers

                pulsado[pointerId] = true;
                posX[pointerId] = event.getX(pointerIndex);
                posY[pointerId] = event.getY(pointerIndex);

                break;
            }
            case MotionEvent.ACTION_MOVE: { // a pointer was moved
                for (int size = event.getPointerCount(), i = 0; i < size; i++) {
                    posX[event.getPointerId(i)] = event.getX(i);
                    posY[event.getPointerId(i)] = event.getY(i);
                }
                break;
            }
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
            case MotionEvent.ACTION_CANCEL: {
                pulsado[pointerId] = false;

                break;
            }
        }

        escribirPosicion();

        return true;
    }
}
